class UserController < ApplicationController

  before_filter :login_required, :only=>['welcome', 'change_password', 'hidden']

  def signup
    @user = User.new(@params[:user])
    @profile = Profile.new
    if request.post?  
      if @user.save
        @profile.user_id = @user.id
        if @profile.save      
          session[:user] = User.authenticate(@user.login, @user.password)
          flash[:message] = "Signup successful"
          redirect_to :controller => 'forum', :action => "list"          
        end
      else
        flash[:warning] = "Signup unsuccessful"
      end
    end
  end

  def login
    if request.post?
      if session[:user] = User.authenticate(params[:user][:login], params[:user][:password])
        flash[:message]  = "Login successful"
        redirect_to_stored
      else
        flash[:warning] = "Login unsuccessful"
      end
    end
  end

  def logout
    session[:user] = nil
    flash[:message] = 'Logged out'
    redirect_to :action => 'login'
  end

  def forgot_password
    if request.post?
      u= User.find_by_email(params[:user][:email])
      if u and u.send_new_password
        flash[:message]  = "A new password has been sent by email."
        redirect_to :action=>'login'
      else
        flash[:warning]  = "Couldn't send password"
      end
    end
  end

  def change_password
    @user=session[:user]
    if request.post?
      @user.update_attributes(:password=>params[:user][:password], 
                :password_confirmation => params[:user][:password_confirmation])
      if @user.save
        flash[:message]="Password Changed"
      end
    end
  end
  
  def hidden
  end
  
  def list
    @user_pages, @users = paginate :users, :per_page => 10
  end
    
  def destroy
    Profile.find(:first, :conditions => ["user_id = ? ", params[:id]]).destroy
    User.find(params[:id]).destroy
    flash[:message]  = "User destroyed"
    redirect_to :action => 'list'
  end
end